package com.xlongwei.accounts.config;

import org.noear.solon.annotation.Component;
import org.noear.solon.core.exception.StatusException;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Handler;
import org.noear.solon.core.handle.Result;
import org.noear.solon.core.route.RouterInterceptor;
import org.noear.solon.core.route.RouterInterceptorChain;
import org.noear.solon.validation.ValidatorException;

import cn.dev33.satoken.exception.NotLoginException;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component(index = -20) // index 为顺序位（不加，则默认为0）
public class AppRouterInterceptor implements RouterInterceptor {
    @Override
    public void doIntercept(Context ctx, Handler mainHandler, RouterInterceptorChain chain)
            throws Throwable {
        // https://solon.noear.org/article/471
        if ("/".equals(ctx.pathNew())) {
            ctx.forward("/index.html");
        }
        Result<?> result = null;
        try {
            chain.doIntercept(ctx, mainHandler);
        } catch (NotLoginException e) {
            result = Result.failure(e.getCode(), "请先登录");
            // ctx.render(Result.failure(e.getCode(), "请先登录"));
        } catch (ValidatorException e) {
            log.warn(e.getMessage());
            result = Result.failure(e.getCode(), "参数有误");
        } catch (StatusException e) {
            if (e.getCode() == 404) {
                ctx.status(e.getCode());
            } else {
                result = Result.failure(e.getCode(), e.getMessage());
            }
        } catch (Throwable e) {
            log.warn(e.getMessage());
            result = Result.failure(500, "服务出错");
        }
        if (result != null) {
            // ctx.result供LoggingRouterInterceptor输出响应
            ctx.result = result;
            ctx.render(result);
        }
    }
}
